<?php
declare (strict_types = 1);

namespace app\middleware;


use think\facade\Db;
use think\Response;
use think\Request;



class AdminLogin
{

    /**
     * 处理请求
     *
     * @param Request $request
     * @param \Closure    $next
     * @throws
     * @return Response
     */
    public function handle(Request $request, \Closure $next):Response
    {
        try{
            //获取登录token
            $token = $request->header('authorization');
            if(!$token){
                throw new \Exception('您未登录，请登录后操作!');
            }
            //验证token
            $token_data = unserialize(encryptCode($token,'DECODE',BASE_DOMAIN));
            if(!$token_data || !isset($token_data['uid']) || !isset($token_data['key'])) {
                throw new \Exception('登录环境发生变化，请重新登录！');
            }

            //验证用户及状态
            $user = Db::name('user')->find($token_data['uid']);
            if(!$user){
                throw new \Exception('您的账号被注销！');
            }
            if(!$user['status']){
                throw new \Exception('您的账号被冻结，请联系管理员！');
            }

            //验证单点登录
            $key = md5($user['id'].$user['ip'].$user['last_login_time']);
            if($key !== $token_data['key']){
                throw new \Exception('您的账号已下线！');
            }

            return $next($request);
        }catch (\Exception $e){
            $err=[
                'code' => 4003,
                'msg'  => $e->getMessage(),
                'data' => []
            ];
            json($err)->send();exit;
        }
    }
}
